const db = require('../../config/database');

class Instruction {
  constructor(
    id = null,
    taskId,
    taskType,
    palletId,
    startLocation,
    targetLocation,
    startDevice,
    endDevice,
    materialCode,
    materialName,
    executeQuantity,
    status, // 将instructionResult改为status
    completionMethod,
    completionTime
  ) {
    this.id = id;
    this.taskId = taskId;
    this.taskType = taskType;
    this.palletId = palletId;
    this.startLocation = startLocation;
    this.targetLocation = targetLocation;
    this.startDevice = startDevice;
    this.endDevice = endDevice;
    this.materialCode = materialCode;
    this.materialName = materialName;
    this.executeQuantity = executeQuantity;
    this.status = status; // 指令状态：not_issued(未下发)、issued(已下发)、executing(正在执行)、completed(已完成)、cancelled(已撤销)
    this.completionMethod = completionMethod;
    this.completionTime = completionTime;
  }

  // 保存指令
  save(callback) {
    const sql = `
      INSERT INTO instructions (
        task_id, task_type, pallet_id, start_location, target_location,
        start_device, end_device, material_code, material_name,
        execute_quantity, status, completion_method, completion_time
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;

    const params = [
      this.taskId, this.taskType, this.palletId, this.startLocation, this.targetLocation,
      this.startDevice, this.endDevice, this.materialCode, this.materialName,
      this.executeQuantity, this.status, this.completionMethod, this.completionTime
    ];

    db.run(sql, params, function(err) {
      if (err) {
        return callback(err);
      }
      callback(null, { id: this.lastID });
    });
  }

  // 获取所有指令
  static findAll(callback) {
    const sql = 'SELECT * FROM instructions ORDER BY id DESC';
    db.all(sql, [], (err, rows) => {
      if (err) {
        return callback(err);
      }
      callback(null, rows);
    });
  }

  // 获取当前指令（未完成的指令）
  static findCurrentInstructions(callback) {
    const sql = `SELECT * FROM instructions WHERE status IN ('not_issued', 'issued', 'executing') ORDER BY id DESC`;
    db.all(sql, [], (err, rows) => {
      if (err) {
        return callback(err);
      }
      callback(null, rows);
    });
  }

  // 获取历史指令（已完成和已撤销的指令）
  static findHistoryInstructions(callback) {
    const sql = `SELECT * FROM instructions WHERE status IN ('completed', 'cancelled') ORDER BY id DESC`;
    db.all(sql, [], (err, rows) => {
      if (err) {
        return callback(err);
      }
      callback(null, rows);
    });
  }

  // 根据ID获取指令
  static findById(id, callback) {
    const sql = 'SELECT * FROM instructions WHERE id = ?';
    db.get(sql, [id], (err, row) => {
      if (err) {
        return callback(err);
      }
      callback(null, row);
    });
  }

  // 根据任务ID获取指令
  static findByTaskId(taskId, callback) {
    const sql = 'SELECT * FROM instructions WHERE task_id = ?';
    db.all(sql, [taskId], (err, rows) => {
      if (err) {
        return callback(err);
      }
      callback(null, rows);
    });
  }

  // 获取最大ID
  static getMaxId(callback) {
    const sql = 'SELECT MAX(id) as maxId FROM instructions';
    db.get(sql, [], (err, row) => {
      if (err) {
        return callback(err);
      }
      callback(null, row);
    });
  }

  // 更新指令状态
  static updateStatus(id, status, completionMethod, completionTime, callback) {
    const sql = `
      UPDATE instructions 
      SET status = ?, completion_method = ?, completion_time = ?
      WHERE id = ?
    `;
    
    const params = [status, completionMethod, completionTime, id];
    
    db.run(sql, params, function(err) {
      if (err) {
        return callback(err);
      }
      callback(null, { updated: this.changes > 0 });
    });
  }

  // 更新任务号
  static updateTaskId(id, taskId, callback) {
    const sql = `
      UPDATE instructions 
      SET task_id = ?
      WHERE id = ?
    `;
    
    const params = [taskId, id];
    
    db.run(sql, params, function(err) {
      if (err) {
        return callback(err);
      }
      callback(null, { updated: this.changes > 0 });
    });
  }

  // 强制过账指令
  static forcePost(id, callback) {
    const sql = `
      UPDATE instructions 
      SET status = 'completed', completion_method = 'force_posted', completion_time = datetime('now')
      WHERE id = ? AND status IN ('not_issued', 'issued', 'executing')
    `;
    
    db.run(sql, [id], function(err) {
      if (err) {
        return callback(err);
      }
      callback(null, { updated: this.changes > 0 });
    });
  }

  // 撤销指令
  static cancel(id, callback) {
    const sql = `
      UPDATE instructions 
      SET status = 'cancelled', completion_method = 'cancelled', completion_time = datetime('now')
      WHERE id = ? AND status IN ('not_issued', 'issued', 'executing')
    `;
    
    db.run(sql, [id], function(err) {
      if (err) {
        return callback(err);
      }
      callback(null, { updated: this.changes > 0 });
    });
  }

  // 删除指令
  static delete(id, callback) {
    const sql = 'DELETE FROM instructions WHERE id = ?';
    db.run(sql, [id], function(err) {
      if (err) {
        return callback(err);
      }
      callback(null, { deleted: this.changes > 0 });
    });
  }

  // 创建指令表
  static createTable(callback) {
    const sql = `
      CREATE TABLE IF NOT EXISTS instructions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        task_id TEXT NOT NULL,
        task_type TEXT NOT NULL,
        pallet_id TEXT,
        start_location TEXT,
        target_location TEXT,
        start_device TEXT,
        end_device TEXT,
        material_code TEXT,
        material_name TEXT,
        execute_quantity INTEGER,
        status TEXT DEFAULT 'not_issued', -- 指令状态：not_issued(未下发)、issued(已下发)、executing(正在执行)、completed(已完成)、cancelled(已撤销)
        completion_method TEXT,
        completion_time DATETIME,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `;

    db.exec(sql, (err) => {
      if (err) {
        return callback(err);
      }
      console.log('指令表已创建或已存在');
      callback(null);
    });
  }
}

module.exports = Instruction;